package cn.micai.base.concurrent;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/5/14 9:29
 */
public class SequenceNumber {

    /**
     * 定义匿名子类创建ThreadLocal的变量
     */
    private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };

    /**
     * 下一个序列号
     * @return
     */
    public int getNextNum() {
        seqNum.set(seqNum.get() + 1);
        return seqNum.get();
    }

    private static class TestClient extends Thread {

        private SequenceNumber sn;

        public TestClient(SequenceNumber sn) {
            this.sn = sn;
        }

        /**
         * 线程产生序列号
         */
        @Override
        public void run() {
            for (int i=0; i<3; i++) {
                System.out.println("thread[" + Thread.currentThread().getName() + "] " +
                        "sn[" + sn.getNextNum() + "]");
            }
        }
    }

    public static void main(String [] args) {
        SequenceNumber sn = new SequenceNumber();
        TestClient t1 = new TestClient(sn);
        TestClient t2 = new TestClient(sn);
        TestClient t3 = new TestClient(sn);
        t1.start();
        t2.start();
        t3.start();
    }

}
